package com.jniu.customviewprogram.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.annotation.NonNull;
import android.support.v4.widget.ViewDragHelper;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

/**
 * Created by jniu on 2017/8/24.
 */

public class SlideBackLayout extends FrameLayout {

    private Activity mActivity;//当前Activity
    private ViewGroup decorView;
    private View rootView;

    private ViewDragHelper viewDragHelper;//Drag助手类

    private Paint paint;
    private int screenWidth;
    private int screenHeight;
    private float slideWidth;

    private int curSlideX;


    public SlideBackLayout(@NonNull Context context) {
        super(context);
        init(context);
    }

    private void init(Context context){
        mActivity = (Activity) context;

        viewDragHelper = ViewDragHelper.create(this, new DragCallback());
        viewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);

        paint = new Paint();
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
        paint.setColor(Color.GRAY);
    }

    public void bind(){

        decorView = (ViewGroup) mActivity.getWindow().getDecorView();
        rootView = decorView.getChildAt(0);
        decorView.removeView(rootView);
        this.addView(rootView);
        decorView.addView(this);

        DisplayMetrics metrics = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
        slideWidth = screenWidth * 0.28f;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return viewDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        viewDragHelper.processTouchEvent(event);
        return true;
    }

    private class DragCallback extends ViewDragHelper.Callback {

        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            return false;
        }

        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            //当前回调，松手时触发，比较触发条件和当前的滑动距离
            int left = releasedChild.getLeft();
            if(left <= slideWidth){
                viewDragHelper.settleCapturedViewAt(0,0);
            }else{
                viewDragHelper.settleCapturedViewAt(screenWidth,0);
            }
            invalidate();
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            curSlideX = left;
            invalidate();
            if (changedView == rootView && left >= slideWidth) {
                mActivity.finish();
            }
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            left = left > 0 ? left : 0;
            return left;
        }

        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
            return 0;
        }

        @Override
        public void onEdgeDragStarted(int edgeFlags, int pointerId) {
            //触发边缘时回调，主动捕捉rootView
            viewDragHelper.captureChildView(rootView,pointerId);
        }
    }

    @Override
    public void computeScroll() {
        if (viewDragHelper.continueSettling(true)) {
            invalidate();
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        drawShadow(canvas);
        super.dispatchDraw(canvas);
    }

    private void drawShadow(Canvas canvas) {
        canvas.save();
        Shader shader = new LinearGradient(curSlideX-40,0,curSlideX,0,
                new int[]{Color.parseColor("#1edddddd"), Color.parseColor("#6e666666"), Color.parseColor("#9e666666")},
                null, Shader.TileMode.REPEAT);
        paint.setShader(shader);

        RectF rectF = new RectF(curSlideX-40,0,curSlideX,screenHeight);
        canvas.drawRect(rectF,paint);
        canvas.restore();
    }
}
